/blog/archive/
Rustyline is pretty slick
TS: 2020-04-26T17:38:24.467518
So while working on the CLI CMS side of this blog I started writing some really ugly code to handle command line input. Having recently read something about the Rustyline crate I figured I’d try it out.
So the problem I was trying to solve was the trailing newline in stdin io and customizable input prompts. So I added Rustyline and created this little helper function to handle it.
Cargo.toml
[dependencies]
rustyline = "6.1"
main.rs
use rustyline::error::ReadlineError;
use rustyline::Editor;
use std::process::exit;
fn input(prompt: &str) -> String {
let mut editor = Editor::<()>::new();
let readline = editor.readline(&prompt);
match readline {
Ok(line) => {
editor.add_history_entry(line.as_str());
line
},
Err(ReadlineError::Interrupted) => {
exit(0)
},
Err(ReadlineError::Eof) => {
exit(1)
}
Err(err) => {
println!("Error: {:?}", err);
exit(1)
}
}
}
Now I can just do these simple assignments, with the bonus of better error handling and CTRL-C exiting.
let thingy = input("Write a thingy: ");
That lets me replace four lines of not exactly the cleanest code for every basic CLI input with a simple one liner, very nice. There are a lot of other features in Rustyline, but that was enough for me to give it the thumbs up.